package org.budo.support.spring.session.strategy.multi;

import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.budo.support.javax.servlet.http.util.CookieBuilder;
import org.budo.support.javax.servlet.http.util.CookieUtil;
import org.budo.support.lang.util.StringUtil;
import org.budo.support.slf4j.Slf4j;
import org.slf4j.Logger;
import org.springframework.session.Session;

/**
 * @author lmw
 * @see org.springframework.session.web.http.HeaderHttpSessionStrategy
 */
public class BudoMultiHttpSessionStrategy extends AbstractBudoMultiHttpSessionStrategy {
    private static final Logger log = Slf4j.getLogger();

    public String getRequestedSessionId(HttpServletRequest request) {
        String requestedSessionId = request.getParameter("_token");

        if (StringUtil.isBlank(requestedSessionId)) {
            requestedSessionId = request.getHeader("_token");
        }

        if (StringUtil.isBlank(requestedSessionId)) {
            List<String> cookieValues = CookieUtil.getCookieValue(request.getCookies(), "_token");
            if (null == cookieValues || cookieValues.isEmpty()) {
                //
            } else if (cookieValues.size() == 1) {
                requestedSessionId = cookieValues.get(0);
            } else {
                log.error("there is more than one cookie value for key _token, " + StringUtil.join(cookieValues.toArray()));
                requestedSessionId = cookieValues.get(0);
            }
        }

        return requestedSessionId;
    }

    /**
     * @see org.springframework.session.web.http.DefaultCookieSerializer#writeCookieValue(org.springframework.session.web.http.CookieSerializer.CookieValue)
     */
    public void onNewSession(Session session, HttpServletRequest request, HttpServletResponse response) {
        CookieUtil.removeCookie(response, "_token");

        Cookie cookie = new CookieBuilder("_token", session.getId()) //
                .setHttpOnly(true) //
                .setPath(request.getContextPath() + "/") //
                .toCookie();

        response.addCookie(cookie);
    }

    public void onInvalidateSession(HttpServletRequest request, HttpServletResponse response) {
        CookieUtil.removeCookie(response, "_token");
    }
}
